package logic

import (
	"fmt"
	"strconv"

	"gitee.com/firewing_group/model/ctxdata"
	"gitee.com/firewing_group/model/model/stadvertisement"
	"gitee.com/firewing_group/model/model/sttempsuanli"
	"gitee.com/firewing_group/model/model/stuser"
	"gitee.com/firewing_group/txproxy/utils"
)

const OneDay = 86400

func GetAideReward(cc, animalcc *ctxdata.Cusctx, user *stuser.KuaiMaoUser, _index string, _validity int) error {

	origin := "advertisement" + strconv.FormatInt(TodayTime(cc), 10)
	id := utils.Sha1(fmt.Sprintf("%v%v", user.ID.Hex(), origin))
	//一般临时算力为 0.5，逢 5 翻 5 倍
	var suanLi int64 = 500000
	lastAd := stadvertisement.GetLastAds(cc, 2, user.UserName)
	if lastAd == nil {
		err := fmt.Errorf("%s", "找不到最近的广告记录")
		cc.Errf("err_%v", err)
		return err
	} else {
		cc.Logf("第轮_%v", lastAd.Number)
		if lastAd.Inform[_index].IsRewarded {
			err := fmt.Errorf("%s", "已领取奖励")
			cc.Errf("err_%v", err)
			return err
		}
		if lastAd.Inform[_index].LookTime == 0 {
			err := fmt.Errorf("%s", "未看视频")
			cc.Errf("err_%v", err)
			return err
		}
	}
	suanLi *= lastAd.Inform[_index].BoomFactor
	suanLi /= 100
	suanLi *= lastAd.Inform[_index].LookFactor
	suanLi /= 100
	if lastAd.Inform[_index].ClickTime != 0 {
		suanLi *= lastAd.Inform[_index].ClickFactor
		suanLi /= 100
	}

	lastAd.UpdateAdRewarded(cc, _index)
	tempSuanLi := sttempsuanli.FindByID(animalcc, id)
	if tempSuanLi == nil {
		sttempsuanli.NewAndInsert(animalcc, id, origin, user.ID.Hex(), "dialog.temporary_power_of_video", TodayTime(cc), TodayTime(cc)+int64(_validity)*OneDay, suanLi)
	} else {
		tempSuanLi.UpdateSuanli(animalcc, suanLi)
	}
	addmoney := lastAd.Inform[_index].Money
	addmoney *= lastAd.Inform[_index].BoomFactor
	addmoney /= 100
	addmoney *= lastAd.Inform[_index].LookFactor
	addmoney /= 100
	if lastAd.Inform[_index].ClickTime != 0 {
		addmoney *= lastAd.Inform[_index].ClickFactor
		addmoney /= 100
	}
	user.AddB(animalcc, addmoney)
	return nil
}
